package org.toy.wechat.gym.rpc;

import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.HttpClient;
import org.springframework.stereotype.Component;
import org.toy.wechat.core.common.exception.BusinessException;
import org.toy.wechat.core.constants.WxConstants;
import org.toy.wechat.gym.rpc.model.WxSession;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 微信rpc
 * @Author devin
 * @Date: 2020/2/22 0022 21:44
 */
@Component
public class WxRpc {

    public WxSession codeToSession(String wxCode) throws BusinessException {

        //设置请求参数
        Map<String, String> params = new HashMap<>();
        params.put(WxConstants.FIELD_NAME_OF_APP_ID, WxConstants.APP_ID);
        params.put(WxConstants.FIELD_NAME_OF_APP_SECRET, WxConstants.APP_SECRET);
        params.put(WxConstants.FIELD_NAME_OF_GRANT_TYPE, WxConstants.GRANT_TYPE);
        params.put(WxConstants.FIELD_NAME_OF_JS_CODE, wxCode);

        //发起请求
        String httpResult;
        try{
            httpResult = HttpClient.get(WxConstants.CODE_TO_SESSION_URL).queryString(params).asString();
        }
        catch (Exception e) {
            throw new BusinessException();
        }
        if (null == httpResult) {
            throw new BusinessException("微信服务异常");
        }

        return JSONObject.parseObject(httpResult, WxSession.class);
    }
}
